# @Time : 2020/7/29 14:40
# @Author : Fioman 
# @Phone : 13149920693
import cv2 as cv
import numpy as np

"""
cv.arcLength() 用于计算轮廓的长度,语法格式为:
retval = cv2.arcLength(curve,closed)
curve是轮廓.
closed是布尔类型,用来表示轮廓是否是封闭的.该值为True时,表示轮廓是封闭的.
查找所有的轮廓,并将所有的轮廓的周长大于平均值的求出来.
"""
img = cv.imread("contours4.jpg")
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

T, thresOtsu = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
image, contours, hierarchy = cv.findContours(thresOtsu, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
lengthList = [cv.arcLength(contour,True) for contour in contours if cv.arcLength(contour,True) > 100]
lengthSum = sum(lengthList)
lengthAvg = lengthSum / len(lengthList)
for index,length in enumerate(lengthList):
    print("第 {} 个轮廓的周长是: {}".format(index,length))
print("平均周长是: {}".format(lengthAvg))

lengthOverAvg = [length for length in lengthList if length >= lengthAvg]
print("大于平均长度的值是: {}".format(lengthOverAvg))